<template>
  <dv-border-box-1 style="height:100%">
    <div id="border">
      <!-- 待添加用户 -->
      <el-form
        v-if="!isRoleDialog"
        ref="useraddForm"
        :inline="true"
        width="100%"
        :rules="RulesuserAddForm"
        :model="pojoAddUser"
        class="demo-form-inline"
      >
        <el-form-item label="待添加用户" prop="username">
          <el-input readonly v-model="pojoAddUser.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-button icon="el-icon-plus" type="primary" @click="addUser">确认添加</el-button>
        <el-button type="primary" @click="resetUserAddForm('useraddForm')">置空</el-button>
        <el-button style="float:right" icon="el-icon-plus" type="primary" circle @click="handleAdd"></el-button>
      </el-form>
      <el-table
        highlight-current-row
        @current-change="clickCurrentChange"
        max-height="480"
        :data="
          list.filter(
            data =>
              !searchUser || data.rname.toLowerCase().includes(searchUser.toLowerCase())
          )
        "
       
      >
        <el-table-column  label="序号" type="index"></el-table-column>
        <el-table-column width="140px" label="角色编号" prop="rid"></el-table-column>
        <el-table-column width="120px" label="角色名" prop="rname"></el-table-column>
        <el-table-column label="状态" prop="state">
          <template slot-scope="scope">
            <el-tag :type="scope.row.state === '1' ? '' : 'info'">
              {{
              scope.row.state | stateFilter
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column width="120px"  v-if="!isRoleDialog" label="系统角色" prop="issystemrole">
          <template slot-scope="scope">
            <el-tag :type="scope.row.issystemrole === '1' ? '' : 'info'">
              {{
              scope.row.issystemrole==='1'?'系统角色':'自定义角色'
              }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column width="150px" v-if="!isRoleDialog" label="创建时间" prop="createtime">
          <template slot-scope="scope">
            {{
            scope.row.createtime | dateFilter
            }}
          </template>
        </el-table-column>
        <el-table-column width="150px"  v-if="!isRoleDialog" label="最后更新时间" prop="updatetime">
          <template slot-scope="scope">
            {{
            scope.row.updatetime | dateFilter
            }}
          </template>
        </el-table-column>
        <el-table-column width="120px"  v-if="!isRoleDialog" label="创建人" prop="createuser"></el-table-column>
        <el-table-column fixed="right" align="right" :width="isRoleDialog?'100px':'250px'">
          <template slot="header" slot-scope="scope">
            <el-input v-model="searchUser" size="mini" placeholder="输入关键字搜索" />
          </template>
          <template v-if="!isRoleDialog" slot-scope="scope">
            <el-popover
              style="background-color:black"
              trigger="hover"
              placement="left"
              width="70px"
            >
              <el-button
                size="mini"
                type="success"
                icon="el-icon-edit"
                plain
                @click="handleEdit(scope.row.rid)"
              >编辑</el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-remove"
                @click="handleDelete(scope.row.rid)"
              >弃用</el-button>
              <el-button type="success" size="mini" plain slot="reference">操作</el-button>
            </el-popover>
            <el-button size="mini" type="warning" plain @click="handleAddUser(scope.row.rid)">添加用户</el-button>
            <el-button size="mini" type="primary" @click="handleAddPermission(scope.row.rid)">添加权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 编辑标签Dialog -->
      <el-dialog title="角色编辑" :visible.sync="dialogFormVisible" width="550px">
        <el-collapse v-model="activeName" style="height:100%" accordion>
          <el-collapse-item v-if="!isAddRole" title="权限" name="permissionList">
            <el-table
              highlight-current-row
              max-height="500"
              :data="
          PermissionList.filter(
            data =>
              !searchPermission || data.pname.toLowerCase().includes(searchPermission.toLowerCase())
          )
        "
              style="width: 100%"
            >
              <el-table-column label="序号" type="index"></el-table-column>
              <el-table-column label="权限编号" prop="pid"></el-table-column>

              <el-table-column label="权限名" prop="pname"></el-table-column>
              <el-table-column label="描述" prop="pdesc"></el-table-column>
              <el-table-column align="right" width="150">
                <template slot="header" slot-scope="scope">
                  <el-input v-model="searchPermission" size="mini" placeholder="输入关键字搜索" />
                </template>
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    plain
                    @click="handleDeletePermission(scope.row.pid)"
                  >取消授权</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>

          <el-collapse-item title="角色信息" name="roleInfo">
            <el-form
              :model="pojo"
              ref="pojoForm"
              :rules="rules"
              label-position="right"
              label-width="100px"
              size="mini"
            >
              <el-form-item label="角色名称" prop="rname">
                <el-input width="60px" v-model="pojo.rname" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="状态" prop="state">
                <el-select v-model="pojo.state" clearable placeholder="请选择">
                  <el-option
                    v-for="item in stateOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <span style="float: left">{{ item.label }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="!isAddRole" label="创建时间" prop="createtime">
                <el-input readonly width="60px" v-model="pojo.createtime" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item v-if="!isAddRole" label="最后更新时间" prop="updatetime">
                <el-input readonly width="60px" v-model="pojo.updatetime" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item v-if="!isAddRole" label="创建人" prop="createuser">
                <el-input readonly width="60px" v-model="pojo.createuser" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button
                type="primary"
                @click="
              pojo.rid === null ? addRole('pojoForm') : updateData('pojoForm')
            "
              >{{ this.pojo.rid === null ? "添加" : "修改" }}</el-button>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-dialog>

      <!-- 用户选择组件 -->
      <el-dialog title="添加用户" :visible.sync="dialogUserVisible" width="500px">
        <admin-app @option-user="optionUser" :isDialog="true"></admin-app>
      </el-dialog>
      <!-- 权限选择组件 -->
      <el-dialog title="添加权限" :visible.sync="dialogPermissionVisivle" width="500px">
        <permission-app @option-permission="optionPermission" :isDialog="true"></permission-app>
      </el-dialog>
    </div>
  </dv-border-box-1>
</template>
<script>
import roleApi from "@/api/role";
import permissionApp from "@/views/user/permission.vue";
import adminApp from "@/views/user/admin.vue";
import moment from "moment";
const stateOptions = [
  { state: "0", statename: "弃用" },
  { state: "1", statename: "使用中" }
];
export default {
  components: {
    adminApp,
    permissionApp
  },
  props: {
    isRoleDialog: Boolean
  },
  data() {
    return {
      PermissionList: [], //用户的权限列表
      activeName: "roleInfo",
      isAddRole: false, //是否为添加角色
      list: [],
      searchUser: "",
      searchPermission: "",
      dialogFormVisible: false, //角色编辑窗口
      pojo: {
        rid: null,
        rname: "",
        createtime: "",
        createuser: "",
        updatetime: "",
        state: ""
      },
      stateOptions: [
        {
          value: "1",
          label: "使用",
          tag: "use"
        },
        {
          value: "0",
          label: "不使用",
          tag: "not use"
        }
      ],
      //待添加用户信息
      pojoAddUser: {
        username: "",
        userid: "",
        rid: ""
      },
      //待添加权限信息
      pojoAddPermission: {
        pid: "",
        rid: ""
      },
      rules: {
        rname: [{ required: true, message: "角色名不能为空", trigger: "blur" }],
        state: [{ required: true, message: "状态不能为空", trigger: "blur" }]
      },
      RulesuserAddForm: {
        username: [
          { required: true, message: "待添加用户不能为空", trigger: "blur" }
        ]
      },
      dialogUserVisible: false, //添加用户组件
      dialogPermissionVisivle: false //添加权限组件
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      roleApi.getList().then(resp => {
        const respData = resp.data;
        if (respData.flag) {
          this.list = respData.data;
        }
      });
    },
    /**
     * 打开编辑窗口
     */
    handleEdit(id) {
      this.handleAdd();
      this.isAddRole = false;
      roleApi.getById(id).then(resp => {
        const respData = resp.data;
        if (respData.flag) {
          this.pojo = respData.data;
        } 
      });
      this.getPermissionListByRid(id);
    },
    /**
     * 根据角色id获取权限列表
     */
    getPermissionListByRid(rid) {
      roleApi.getPermissionListById(rid).then(resp => {
        const respData = resp.data;
        if (respData.flag) {
          this.PermissionList = respData.data;
        } else {
          this.$message({
            type: "warning",
            message: respData.message
          });
        }
      });
    },
    /**
     * 修改角色
     */
    updateData() {
      this.$refs.pojoForm.validate(valid => {
        if (valid) {
          roleApi.update(this.pojo).then(resp => {
            if (resp.data.flag) {
              this.$message({
                type: "success",
                message: resp.data.message
              });
              this.dialogFormVisible = false;
            } else {
              this.$message({
                type: "warning",
                message: resp.data.message
              });
            }
          });
        }
      });
    },
    /**
     * 弃用角色
     */
    handleDelete(id) {
      this.$confirm("确定弃用此角色吗?", "提示", {
        confirmButtonText: "弃用",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          roleApi.delete(id).then(resp => {
            this.$message({
              type: resp.data.flag ? "success" : "error",
              message: resp.data.message
            });
            if (resp.data.flag) {
              this.fetchData();
            }
          });
        })
        .catch(() => {
          return;
        });
    },
    /**
     * 打开添加用户窗口
     */
    handleAddUser(rid) {
      this.dialogUserVisible = true;
      this.pojoAddUser.rid = rid;
    },
    /**
     * 打开添加权限窗口
     */
    handleAddPermission(rid) {
      this.dialogPermissionVisivle = true;
      this.pojoAddPermission.rid = rid;
    },
    /**
     * 打开编辑窗口
     */
    handleAdd() {
      this.isAddRole = true;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["pojoForm"].resetFields();
        
      });
      this.pojo.rid=null
      //console.log(this.pojo.rid)
    },
    /**
     * 添加角色
     */
    addRole() {
      this.$refs.pojoForm.validate(valid => {
        if (valid) {
          roleApi.addRole(this.pojo).then(resp => {
            if (resp.data.flag) {
              this.$message({
                type: "success",
                message: resp.data.message
              });
              this.fetchData();
              this.dialogFormVisible = false;
            } else {
              this.$message({
                type: "warning",
                message: resp.data.message
              });
            }
          });
        } else {
          if (this.pojo.rname === "") {
            this.$message({
              type: "warning",
              message: "角色名不能为空"
            });
          } else if (this.pojo.state === "") {
            this.$message({
              type: "warning",
              message: "状态不能为空"
            });
          }
        }
      });
    },
    /**
     * 角色添加用户
     */
    addUser() {
      this.$refs.useraddForm.validate(valid => {
        if (valid) {
          roleApi
            .addUser(this.pojoAddUser.rid, this.pojoAddUser.userid)
            .then(resp => {
              if (resp.data.flag) {
                this.$message({
                  type: "success",
                  message: resp.data.message
                });
                this.$nextTick(() => {
                  this.$refs["useraddForm"].resetFields();
                });
              } else {
                this.$message({
                  type: "warning",
                  message: resp.data.message
                });
              }
            });
        }
      });
    },
    /**
     * 角色添加权限
     */
    addPermission() {
      roleApi
        .addPermission(this.pojoAddPermission.rid, this.pojoAddPermission.pid)
        .then(resp => {
          if (resp.data.flag) {
            this.$message({
              type: "success",
              message: resp.data.message
            });
          } else {
            this.$message({
              type: "warning",
              message: resp.data.message
            });
          }
        });
    },
    /**
     * 删除角色权限 pid:权限id
     */
    handleDeletePermission(pid) {
      this.$confirm("确定取消此权限吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          roleApi.deletePermissionById(this.pojo.rid, pid).then(resp => {
            this.$message({
              type: resp.data.flag ? "success" : "error",
              message: resp.data.message
            });
            if (resp.data.flag) {
              this.getPermissionListByRid(this.pojo.rid);
            }
          });
        })
        .catch(() => {
          return;
        });
    },
    optionUser(currentRow) {
      if (currentRow.isblack === "1") {
        this.$message({
          type: "warning",
          message: "该用户已被拉入黑名单！"
        });
        return false;
      }
      this.pojoAddUser.username = currentRow.username; //用户名
      this.pojoAddUser.userid = currentRow.id;
      this.dialogUserVisible = false;
    },
    /**
     * 选择添加的权限
     */
    optionPermission(currentRow) {
      this.pojoAddPermission.pid = currentRow.pid; //权限id
      this.addPermission();
      this.dialogPermissionVisivle = false;
    },
    /**
     * 置空待添加用户
     */
    resetUserAddForm(formName) {
      this.$refs[formName].resetFields();
    },
    /**
     * 点击某行后触发该方法
     */
    clickCurrentChange(currentRow) {
      //点击后将数据传递到父组件（文章管理），触发父组件的option-category，父组件可以在option-category这个事件对应的处理函数中接收数据
      this.$emit("option-role", currentRow);
    }
  },
  filters: {
    stateFilter(state) {
      const obj = stateOptions.find(obj => {
        return obj.state === state;
      });
      return obj ? obj.statename : null;
    },
    dateFilter(input, formatString = "YYYY-MM-DD HH:mm:ss") {
      return moment(input).format(formatString);
    }
  }
};
</script>
<style scoped>
#border {
  padding: 20px;
}
</style>
